import { login, logout, getInfo, getMenu } from '@/api/login'
import { getTokenName, setTokenName,getTokenValue, setTokenValue, removeToken, setId } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import { allPagesRoutes } from '@/router';

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      tokenName: getTokenName(),
      tokenValue: getTokenValue(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      nickName: '',
    }),
    actions: {
      // 登录
      login(userInfo) {
        const account = userInfo.account.trim()
        const password = userInfo.password
        const loginType = userInfo.loginType
        const code = userInfo.code
        // const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(account, password, loginType, code).then(res => {
            console.log('res', res) // 测试用，后面删除，打印re
            setTokenName('token')
            setTokenValue(res.data.token)
            localStorage.setItem('userInfo', JSON.stringify(res.data)) // 测试用，后面删除，打印re.dat
            this.tokenName = 'token'
            this.tokenValue = res.data.token

            this.id = res.data.id
            this.nickName = res.data.nickname
            this.avatar = res.data.avatar
            this.permissions = res.data.roles
            console.log("this.permissions ==> {}", this.permissions)
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo(this.id).then(res => {
            console.log("获取用户信息 ==> {}", res)
            const user = res.data
            //const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              // this.permissions = res.roles
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.nickName = user.nickname
            this.permissions = [100,10010,10030,200,20010,20011,20012,20013,20014,300,30010,30020,100,400,40010,40011,40012,40013,40014,40015,40016,900,90010,600,60010]
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
        })
      },
      setPermissions(permissions) {
        this.permissions = permissions
      },
      getPermissions() {
        // 从localStorage中获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        
        // 如果store中有权限信息，优先使用store中的
        if (this.permissions && this.permissions.length > 0) {
          console.log("返回store中的权限ID数组 ==> {}", this.permissions);
          return this.permissions;
        }
        
        // 如果localStorage中有权限信息，使用localStorage中的
        if (userInfo && userInfo.roles && userInfo.roles.length > 0) {
          this.permissions = userInfo.roles;
          this.roles = userInfo.roles;
          console.log("返回localStorage中的权限ID数组 ==> {}", userInfo.roles);
          return userInfo.roles;
        }
        
        // 如果都没有，返回空数组
        console.log("没有找到权限ID数组，返回空数组");
        return [];
      },
    }
  })

export default useUserStore
